﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Web.Security;
using B10.Helpers;

namespace Facebook
{
    public static class FacebookConnect
    {
        private readonly static string _facebookCookieName = ".FCBJUNTOSAUTH";

        #region Properties and Instance members
        public static bool IsConnected
        {
            get
            {
                //Note that this can be insufficient in certain cases, such as when the user logs out of facebook in another window
                //at that point the session/access_token is invalid 
                bool result = (SessionKey != null && UserID > 0);
                //if (!result)
                //    DeleteCookie();
                return result;
            }
        }


        public static string SessionKey
        {
            get
            {
                string sessionKey = GetFacebookCookieValue();
                return sessionKey;
            }
        }

        public static long UserID
        {
            get;
            set;
        }

        public static string GetUserName()
        {
            if (!IsConnected)
            {
                return null;
            }
            return GetFacebookUserName();
        }

        public static bool PublishToWall()
        {
            try
            {
                FacebookAPI api = new FacebookAPI("157980054219397|4756077d2d87d25a92b71a93-100001562584359|4RRwpi6KKw0ReaQA5WIdSnWzmS0");
                JSONObject me = api.Post("/" + "100001562584359" + "/" + "feed",
                    new Dictionary<string, string>() { 
                        {"message","To jest wiadomość testowa aaa bbbbb cccccc ddddddddd eeeeee"
                        + "fffffffffff hhhhhhhhhhhhhhhhhhhhh jjjjjjjjjjjjjjj"},
                  {"link","http://www.example.com/article.html"},
                  {"picture" ,"http://www.example.com/article-thumbnail.jpg"},
                  { "name","Article Title"},
                  {"caption","Caption for the link"},
                  {"description","Longer description of the link"},
                  {"actions","{\"name\": \"View on Zombo\", \"link\": \"http://www.zombo.com\"}"},
                  {"privacy","{\"value\": \"ALL_FRIENDS\"}"}
                });
            }
            catch
            {
                return false;
            }
            return true;
        }

        public static string AccessToken
        {
            get;
            set;
        }
        #endregion

        #region Methods


        internal static void Init(string token, long userId)
        {
            if (!FacebookConnect.IsConnected)
            {
                AccessToken = token;
                UserID = userId;
            }
        }
        
        internal static void Terminate()
        {
            DeleteCookie();
            UserID = 0;
        }

        private static string GetFacebookUserName()
        {
            if (HttpContext.Current == null)
                return null;
            HttpCookie authCookie = HttpContext.Current.Request.Cookies[_facebookCookieName];

            if (authCookie == null)
            {
                return SetFacebookUser();
            }
            else
            {
                FormsAuthenticationTicket authTicket = null;
                try
                {
                    authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                }
                catch
                {
                    // Log exception details (omitted for simplicity)
                    return null;
                }
                if (authTicket == null)
                    return null;
                if (authTicket.UserData != UserID.ToString())
                    return SetFacebookUser();
                return authTicket.Name;
            }
        }

        private static string SetFacebookUser()
        {
            FacebookAPI api = new FacebookAPI(FacebookConnect.AccessToken);
            JSONObject me = api.Get("/" + FacebookConnect.UserID, new Dictionary<string, string>() { 
                {"fields", "id,name,first_name,last_name,link,birthday,email,gender,picture,about"} });
            if (me != null)
            {
                IProfileService profileService = new ProfileService();
                int id = profileService.CreateFacebookProfile(me);
                return CreateFacebookUserNameCookie(id.ToString());
            }
            return null;
        }

        private static string CreateFacebookUserNameCookie(string userName)
        {
            if (string.IsNullOrEmpty(userName))
                return null;
            FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
                1, userName, DateTime.Now, DateTime.Now.AddHours(1), true, UserID.ToString());
            // Now encrypt the ticket.
            string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
            // Create a cookie and add the encrypted ticket to the
            // cookie as data.
            HttpCookie authCookie =
                         new HttpCookie(_facebookCookieName, encryptedTicket);
            // Add the cookie to the outgoing cookies collection.
            HttpContext.Current.Response.Cookies.Add(authCookie);
            return userName;
        }

        private static void DeleteCookie()
        {
            if (HttpContext.Current == null)
                return;
            HttpCookie authCookie = HttpContext.Current.Request.Cookies[_facebookCookieName];

            if (authCookie != null)
            {
                HttpCookie cookie = new HttpCookie(_facebookCookieName, "NoCookie");
                cookie.Expires = new DateTime(0x7cf, 10, 12);

                HttpContext.Current.Request.Cookies.Remove(_facebookCookieName);
                HttpContext.Current.Request.Cookies.Add(cookie);
            }
        }



        private static string GetFacebookCookieValue()
        {
            string cookieName = "fbsr_" + ConfigurationManager.AppSettings["AppID"];
            HttpCookie c = HttpContext.Current.Request.Cookies[cookieName];
            if (c != null)
                return c.Value;

            return null;
        }
        #endregion

    }
}
